// server/api/skills.post.ts
import { defineEventHandler, readBody, getHeader } from "h3";
import { verifyToken } from "../../utils/auth";

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, "authorization");
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      throw createError({
        statusCode: 401,
        statusMessage: "未提供认证令牌",
      });
    }

    const token = authHeader.slice(7);
    const decoded = verifyToken(token);
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: "令牌无效或已过期",
      });
    }

    const body = await readBody(event);
    const { username, skillName } = body;

    if (!username || !skillName) {
      throw createError({
        statusCode: 400,
        statusMessage: "需要提供用户名和技能名称",
      });
    }

    // 验证技能名称长度
    if (skillName.length > 8) {
      throw createError({
        statusCode: 400,
        statusMessage: "技能名称不能超过8个字符",
      });
    }

    // 查询用户
    const user = await prisma.user.findUnique({
      where: { username: username as string },
      include: {
        skills: true,
      },
    });

    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: "用户不存在",
      });
    }

    // 检查技能数量限制（最多15个）
    if (user.skills.length >= 15) {
      throw createError({
        statusCode: 400,
        statusMessage: "最多只能添加15个技能标签，请删除不必要的技能",
      });
    }

    // 检查技能是否已存在
    const existingSkill = user.skills.find((skill) => skill.name === skillName);
    if (existingSkill) {
      throw createError({
        statusCode: 400,
        statusMessage: "该技能已存在",
      });
    }

    // 创建新技能
    const newSkill = await prisma.skill.create({
      data: {
        userId: user.id,
        name: skillName,
      },
    });

    return {
      code: 201,
      message: "技能添加成功",
      data: newSkill,
    };
  } catch (error: any) {
    console.error("添加技能错误:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || "添加失败",
    });
  }
});
